package com.example.pro1.controller.zhao;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@CrossOrigin//开放前端跨域访问
@Api(tags = "文件上传泽宇贴心版")
@RestController
@RequestMapping("/api/file")
@Slf4j
public class FileUp {
    @RequestMapping("/saveFile")
    public String saveImage(@RequestPart("Imagefile") MultipartFile file){
        if(!file.isEmpty()){
            String uploadPath = "/www/wwwroot/img";
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            //重新随机生成名字
            String filename = UUID.randomUUID().toString() +suffixName;
            File localFile = new File(uploadPath+"/"+filename);
            String visitURL = "http://124.222.54.34/"+filename;
            try {
                file.transferTo(localFile); //把上传的文件保存至本地
                /**
                 * 这里应该把filename保存到数据库,供前端访问时使用
                 */
                System.out.println("保存成功");
                return visitURL;//上传成功，返回保存的文件地址
            }catch (IOException e){
                e.printStackTrace();
                System.out.println("上传失败");
                return "上传失败";
            }

        }
        else{
            System.out.println("文件为空");
            return "上传失败";
        }
    }
}
